package {
	import flash.display.Bitmap;	
	import flash.display.DisplayObject;	
	import flash.events.Event;	
	import flash.display.Loader;	
	import flash.net.URLRequest;	
	import flash.display.Sprite;
	
	public class GalleryImage extends Sprite {
		
		public var image:Bitmap;
		private var request:URLRequest = new URLRequest();
		public var imageLoader:Loader = new Loader();
		private var _w:Number;
		private var _h:Number;
		private var _ratio:Number;
		private var _url:String;
		private var _loading:DisplayObject;

		public function GalleryImage(url:String, w:Number, h:Number, loading : DisplayObject) {
			//set the private variables you created to be the info passed in the constructor from Gallery
			//  so the the info can be used outside of this finction
			_loading = loading;
			_url = url;
			_w = w;
			_h = h;
			//add child to your loading instance immediatly--this way if your images take a while to load
			//  theres no blank spot in your flash
			addChild(_loading);
			//set the request vars request url to be the url passed in the constructor
			request.url = _url;
			//have the imageLoader load the URL
			imageLoader.load(request);
			//on the added event you will run onComplete--when the thumb has been added to the stage
			imageLoader.addEventListener(Event.ADDED, onComplete);
		}
        private function onComplete(event:Event):void {
        	//remove the loading instance so it is not visible under the thumbs
        	removeChild(_loading);
        	//set the ratio for the thumbs by using this logic
			if((imageLoader.width) > (imageLoader.height)){
				_ratio = _w / imageLoader.width;
			} else {
				_ratio = _h / imageLoader.height;				
			}
			//set the scaleX and y
        	imageLoader.content.scaleX = _ratio;
        	imageLoader.content.scaleY = _ratio;
        	//add the thumm to the display list
        	addChild(imageLoader.content);
        	//set the thumb image as a bitmap so we can get the bitmap data in Gallery
			image = imageLoader.content as Bitmap;
		}
	}
}
